package com.iro.blog.web;

import com.iro.blog.Service.BlogsService;
import com.iro.blog.Service.CommentService;
import com.iro.blog.pojo.Comment;
import com.iro.blog.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class Commentcontroller {

    @Autowired
    private CommentService commentService;

    @Autowired
    private BlogsService blogsService;

    @Value("${comment.avatar}")
    private String avatar;

    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId, Model model){
        model.addAttribute("comments",commentService.listCommentByBlogId(blogId));

        return "blog :: commentList";
    }
    @PostMapping("/comments")
    public String post(Comment comment ,HttpSession session){
        Long blogId=comment.getBlog().getId();
        comment.setBlog(blogsService.getBlog(blogId));
        User user= (User) session.getAttribute("user");
        if (user!=null){
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
//            comment.setNickname(user.getNickname());
        }else {
            comment.setAvatar(avatar);
        }

        commentService.saveComment(comment);
        return "redirect:/comments/"+comment.getBlog().getId();
    }
    @GetMapping("/comments/select")
    public String comments1(@PageableDefault(size = 5,sort = {"createTime"},direction = Sort.Direction.DESC) Pageable pageable, Model model){
        System.out.println(commentService.listComment(pageable));
        model.addAttribute("page",commentService.listComment(pageable));
        return "blog";
    }
}
